$(function () {
    // todos 获取新闻列表
    function render(){
        $.ajax({
            method:'GET',
            url:'http://www.liulongbin.top:3006/api/news',
            success({status,msg,data}){
                console.log(data)
                
                if(status !== 200) return alert(msg)
                const newStr = data.map(item=>{
                    const {title,source,cmtcount,tags,img,time} = item 
                    // 调用函数 时间格式转换
                    const newTime = formatData(time) 
                    // 将字符串拆封为数组
                    const newData = tags.split(',')   
                    return `
                    <div class="news-item">
                    <img class="thumb" src="http://www.liulongbin.top:3006${img}" alt="" />
                    <div class="right-box">
                      <h1 class="title">${title}</h1>
                      <div class="tags">
                        <span>${newData[0] || ''}</span>
                        <span>${newData[1] || ''}</span>
                        <span>${newData[2] || ''}</span>
                      </div>
                      <div class="footer">
                        <div>
                          <span>${source}</span>&nbsp;&nbsp;
                          <span>${newTime}</span>
                        </div>
                        <span>评论数：${cmtcount}</span>
                      </div>
                    </div>
                  </div>
                    `
                }).join('')
                $('#news-list').html(newStr)
            }
        })
    }
    render()

    // 定义时间转换函数
    function formatData(timeValue){
      // 获取时间
      const setTimeVal = new Date(timeValue)

      const year = setTimeVal.getFullYear()  //年
      const mouth = setTimeVal.getMonth()+1  //月
      const date = setTimeVal.getDate()      //日
      const hours = setTimeVal.getHours()    //时
      const minutes = setTimeVal.getMinutes() //分
      const seconds = setTimeVal.getSeconds() //秒

      // 补零操作
      const zeroFill = num=> num <10? '0' + num : num
      return [year,mouth,date].map(zeroFill).join('-')+ ' ' + [hours,minutes,seconds].map(zeroFill).join(':')

    }
})
